/*
 * Copyright 2020 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.naja.auth2clientfirst.web;

import com.alibaba.fastjson.JSONObject;
import com.naja.auth2clientfirst.support.ExpandUserAuthoritiesRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClient;
import org.springframework.security.oauth2.client.annotation.RegisteredOAuth2AuthorizedClient;
import org.springframework.security.oauth2.client.web.OAuth2AuthorizedClientRepository;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.reactive.function.client.WebClient;

import javax.servlet.http.HttpServletRequest;

import java.util.HashMap;

import static org.springframework.security.oauth2.client.web.reactive.function.client.ServletOAuth2AuthorizedClientExchangeFilterFunction.clientRegistrationId;
import static org.springframework.security.oauth2.client.web.reactive.function.client.ServletOAuth2AuthorizedClientExchangeFilterFunction.oauth2AuthorizedClient;

/**
 * @author Joe Grandja
 * @since 0.0.1
 */
@Controller
public class AuthorizationController {
	@Autowired
	@Lazy
	private  WebClient webClient;
	@Value("${messages.base-uri}")
	private  String messagesBaseUri;
	@Autowired
	@Lazy
	private OAuth2AuthorizedClientRepository authorizedClientRepository;

	@GetMapping(value = "/authorize", params = "grant_type=authorization_code")
	public String authorizationCodeGrant(Model model,
										 @RegisteredOAuth2AuthorizedClient("messaging-client-a-oidc")
										 OAuth2AuthorizedClient authorizedClient) {
		HashMap userInfo = this.webClient
				.get()
				.uri("localhost:9000/userinfo")
				.attributes(oauth2AuthorizedClient(authorizedClient))
				.retrieve()
				.bodyToMono(HashMap.class)
				.block();
		model.addAttribute("messages", JSONObject.toJSONString(userInfo));

		return "index";
	}

	@GetMapping(value = "/authorized", params = "token")
	public String authorizationFailed(Model model, HttpServletRequest request) {
		OAuth2AuthorizedClient oAuth2AuthorizedClient = authorizedClientRepository
				.loadAuthorizedClient("messaging-client-a-oidc",
						SecurityContextHolder.getContext().getAuthentication(), request);
		model.addAttribute("token", JSONObject.toJSONString(oAuth2AuthorizedClient));
		return "index";
	}

	@GetMapping(value = "/authorized", params = "user")
	public String authorizationUser(Model model, HttpServletRequest request) {
		model.addAttribute("token", JSONObject.toJSONString(SecurityContextHolder.getContext().getAuthentication().getPrincipal()));
		return "index";
	}

	@GetMapping(value = "/authorize", params = "grant_type=client_credentials")
	public String clientCredentialsGrant(Model model) {

		String[] messages = this.webClient
				.get()
				.uri(this.messagesBaseUri)
				.attributes(clientRegistrationId("messaging-client-a-client-credentials"))
				.retrieve()
				.bodyToMono(String[].class)
				.block();
		model.addAttribute("messages", messages);

		return "index";
	}

	@GetMapping(value = "/addAuth")
	public String clientCredentialsGrant1(String name,String[] auth) {
		ExpandUserAuthoritiesRepository userAuthoritiesRepository = ExpandUserAuthoritiesRepository.instance();
		userAuthoritiesRepository.add(name, auth);
		return "index";
	}


}
